#ifndef _HW_CONTROL_H
#define _HW_CONTROL_H

#ifndef __cplusplus
typedef enum {FALSE = 0, TRUE = !FALSE} bool;
#endif

#include "define.h"
#include "stm32f10x.h"

#include "debug_khh.h"
#include "eeprom.h"
#include "timer.h"
#include "uart.h"
#include "eeprom_flycam.h"
#include "sbus.h"
#include "spektrum.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>


extern void GPIO_Configuration(void);
extern void delay_us(uint32_t t);
extern void delay_ms(uint32_t t);
extern void systick_init(void);
extern void Delay_ms(__IO uint32_t nTime);
extern void Delay_100us(__IO uint32_t nTime);

extern void NVIC_Configuration(void);
extern void System_Information();
extern void RCC_Configuration(void);

extern void SysWaitStart(__IO uint32_t n100us);
extern uint32_t SysWaitGet(void);
extern void SysWait(void);
extern uint32_t SystemTick(void);

typedef union
{
	uint16_t h   ;     // h as HALF-WORD
	uint8_t  b[2];     // b as BYTE 0,0
} Union16;

typedef union
{
	uint32_t w   ;     // w as WORD
	uint16_t h[2];     // h as HALF-WORD
	uint8_t  b[4];     // b as BYTE
} Union32;

typedef union
{
	uint64_t d   ;     // d as DOUBLE-WORD
	uint32_t w[2];     // w as WORD
	uint16_t h[4];     // h as HALF-WORD
	uint8_t  b[8];     // b as BYTE
} Union64;

typedef union
{
	float    f;
	uint16_t h[2];     // h as HALF-WORD
	uint8_t  b[4];     // b as BYTE 0,0
} Union_float;

typedef union
{
	double 	 d;
	float    f[2];
	uint16_t h[4];     // h as HALF-WORD
	uint8_t  b[8];     // b as BYTE 0,0
} Union_double;

// MIN/MAX/ABS macros
#define MIN(a,b)			((a<b)?(a):(b))
#define MAX(a,b)			((a>b)?(a):(b))
#define ABS(x)				((x>0)?(x):(-x))
#define CHECK_MIN_MAX(value,min,max) {if(value < min) value = min; else if(value > max) value = max;}

// constants
#define PI		3.14159265359

#define SYS_WAIT					0.5/(DELTA_TICK/1000.0)		// 100(*0.005= 0.5 sec)
#define SYS_TIME_INIT				3.0/(DELTA_TICK/1000.0)		// 600(*0.005= 3 sec)

#define LED1_ON     GPIOA->BRR = GPIO_Pin_4
#define LED1_OFF    GPIOA->BSRR = GPIO_Pin_4
#define LED1_FL     GPIOA->ODR ^= GPIO_Pin_4

#define IR_OFF     GPIOA->BRR = GPIO_Pin_6
#define IR_ON    GPIOA->BSRR = GPIO_Pin_6

extern __IO uint32_t TimingDelay;
extern __IO uint16_t Timer_cnt;
extern volatile uint16_t Gdt_timer_cnt;

extern uint32_t micros(void);
extern uint32_t millis(void);
extern void delay(uint32_t ms);
extern void delayMicroseconds(uint32_t us);
#endif
